﻿// ===============================================================================
// DotNet.Platform 开发框架 2016 版权所有
// ===============================================================================

using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

namespace DotNet.Helper
{
    /// <summary>
    /// 文件日志操作类
    /// </summary>
    public static class LogHelper
    {
        /// <summary>
        /// 记录日志(记录代码所在的类和方法)
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Log(string message)
        {
            StackTrace st = new StackTrace();
            StackFrame sf = st.GetFrame(1);
            var method = sf.GetMethod();
            string msg = $"{DateTimeHelper.FormatDateHasSecond(DateTime.Now)} {method.DeclaringType?.FullName}.{method.Name} {message}";
            Core(msg);
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Message(string message)
        {
            string msg = $"{DateTimeHelper.FormatDateHasSecond(DateTime.Now)} {message}";
            Core(msg);
        }

        private static void Core(string message)
        {
            string folder = DirHelper.RootDirectory;
            string fileName = DateTimeHelper.FormatDate(DateTime.Now, "yyyy-MM-dd") + ".log";
            string path = Path.Combine(folder, "Log", fileName);
            FileHelper.CreateDirectoryByPath(path);

            try
            {
                StreamWriter streamWriter = !File.Exists(path) ? File.CreateText(path) : File.AppendText(path);
                using (streamWriter)
                {
                    streamWriter.WriteLine(message);
                    streamWriter.Flush();
                }
            }
            catch (Exception e)
            {
                DebugHelper.Debug(e.Message);
            }
        }
    }
}